#!/usr/bin/env python
# encoding: utf-8

from rest_framework import (
    viewsets,
    mixins,
)
import uuid
from rest_framework.response import Response
from .serializers import SmsCodeSerializer
from rest_framework.decorators import action
from usercenter.models import CustomerProfile
from usercenter.common.validators import validate_mobilephone
from usercenter.common.errors import get_error_info, MOBILEPHONE_ERROR, CODE_SEND_ERROR
from usercenter.common.redis_keys import PHONE_CODE_KEY, CAPTCHA_CODE_KEY
from usercenter.common.rand import create_rand_code
from django.core.cache import cache
from .sms import xuanwu_sms
from rest_framework import serializers
import logging
logger = logging.getLogger('userauth')

PHONE_CODE_TTL = 15 * 60  # 验证码有效期
PHONE_CODE_GAP = 60  # 验证码输入间隔


class SmsViewSet(viewsets.GenericViewSet):
    """
    发短信接口
    """

    queryset = CustomerProfile.objects.all()
    serializer_class = SmsCodeSerializer
    permission_classes = []

    @action(methods=['post'], detail=False)
    def code(self, request, **kwargs):
        """
        发送短信验证码
        """
        ret = {'code': 0, 'message': ''}
        self.get_serializer().run_validation(request.data)  # 验证输入

        phone = request.data.get('phone', '').strip()
        if not validate_mobilephone(phone):
            ret.update(get_error_info(MOBILEPHONE_ERROR))  # 手机号错误
            return Response(ret, 400)

        # 验证发送频率
        cache_key = PHONE_CODE_KEY % phone
        ttl = cache.ttl(cache_key)
        if ttl > PHONE_CODE_TTL - PHONE_CODE_GAP:
            raise serializers.ValidationError('1分钟内，同一号码只能发送一次短信')
        code = create_rand_code()
        res = xuanwu_sms.send_sms(
            phone,
            code,
            uuid.uuid4()
        )
        if res.result == 0:
            cache.set(cache_key, code, PHONE_CODE_TTL)  # 15分钟有效
        else:
            logger.error('send sms error: %s', res)
            ret.update(get_error_info(CODE_SEND_ERROR))  # 发送失败

        return Response(ret)